﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth;
using TheDFFL.Entities;

namespace TheDFFL.Services
{
    public class TeamService : ITeamService
    {
        private readonly WebConsumer consumer;
        private readonly string accessToken;

        public TeamService(WebConsumer consumer, string accessToken)
        {
            this.consumer = consumer;
            this.accessToken = accessToken;
        }

        public Team GetTeamByKey(string key)
        {
            var serviceEndpoint = new MessageReceivingEndpoint(
                string.Format("http://fantasysports.yahooapis.com/fantasy/v2/team/{0}", key),
                HttpDeliveryMethods.GetRequest
            );

            var request = consumer.PrepareAuthorizedRequest(serviceEndpoint, accessToken);
            var response = consumer.Channel.WebRequestHandler.GetResponse(request);
            var result = XDocument.Load(response.GetResponseReader());

            var team = (from t in result.Descendants(XmlExtensions.YahooNS + "team")
                        select t.ToTeam()).Single();

            return team;
        }

        public IEnumerable<Team> GetAllTeams()
        {
            // Get teams from both Leagues
            var keys = new List<string>() { "nfl.l.146137", "nfl.l.454480" };
            throw new NotImplementedException();
        }

        public IEnumerable<Team> GetTeamsByLeagueKeys(params string[] keys)
        {
            var serviceEndpoint = new MessageReceivingEndpoint(
                string.Format("http://fantasysports.yahooapis.com/fantasy/v2/leagues;league_keys={0}/standings", string.Join(",", keys)),
                HttpDeliveryMethods.GetRequest
            );

            var request = consumer.PrepareAuthorizedRequest(serviceEndpoint, accessToken);
            var response = consumer.Channel.WebRequestHandler.GetResponse(request);
            var result = XDocument.Load(response.GetResponseReader());

            var teams = from t in result.Descendants(XmlExtensions.YahooNS + "team")
                        select t.ToTeam();

            return teams.OrderByDescending(t => t.Wins)
                        .ThenByDescending(t => t.Ties)
                        .ThenByDescending(t => t.Losses)
                        .ThenByDescending(t => t.PointsScored)
                        .ThenByDescending(t => t.PointsAgainst);
        }


        public IEnumerable<Team> GetTeamsByLeagueKey(string key)
        {
            var serviceEndpoint = new MessageReceivingEndpoint(
                string.Format("http://fantasysports.yahooapis.com/fantasy/v2/league/{0}/standings", key),
                HttpDeliveryMethods.GetRequest
            );

            var request = consumer.PrepareAuthorizedRequest(serviceEndpoint, accessToken);
            var response = consumer.Channel.WebRequestHandler.GetResponse(request);
            var result = XDocument.Load(response.GetResponseReader());

            var teams = from t in result.Descendants(XmlExtensions.YahooNS + "team")
                        select t.ToTeam();
            return teams;
        }
    }

    public interface ITeamService
    {
        Team GetTeamByKey(string key);
        IEnumerable<Team> GetTeamsByLeagueKey(string key);
        IEnumerable<Team> GetTeamsByLeagueKeys(params string[] keys);
    }
}
